package org.cms.call;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpRequestBase;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * Created by elnoa on 28/10/14.
 */
public abstract class AbstractCall<TYPE extends HttpRequestBase> {

    private HttpClient httpclient;

    private String access_token;

    private TYPE request;
    private HttpResponse response;


    public HttpClient getHttpclient() {
        return httpclient;
    }

    public String getAccess_token() {
        return access_token;
    }

    protected AbstractCall(HttpClient httpclient, String access_token) {
        this.httpclient = httpclient;
        this.access_token = access_token;
    }

    public TYPE getRequest() {
        return request;
    }

    public HttpResponse getResponse() {
        return this.response;
    }

    public void setRequest(TYPE request) {
        this.request = request;
    }

    public void setResponse(HttpResponse response) {
        this.response = response;
    }

    /**
     *
     * @param entity
     * @return the content of the response as String
     * @throws java.io.IOException
     */
    public String getResponseContentAsString() {
        StringBuilder sb = new StringBuilder();
        try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(this.response.getEntity().getContent()));

            for (String line; null != (line = reader.readLine()); ) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

    abstract AbstractCall invoke();
}
